﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Security.Cryptography;
using System.Xml;
using System.IO.Ports;

namespace GCard
{
    public partial class PortForm : Form
    {
        public PortForm()
        {
            InitializeComponent();
            InitalSerialPort();
        }     

        SerialPort serialPort1 = new SerialPort();
        public void InitalSerialPort()
        {
            cmb_port.Items.AddRange(SerialPort.GetPortNames()); //自动识别串口名
            if (cmb_port.Items.Count > 0)                       //端口号默认值
            {
                cmb_port.SelectedIndex = 0;
            }
            cmb_BaudRate.SelectedIndex = 5;//波特率默认值
            cmb_DataBits.SelectedIndex = 2;//数据位默认值
            cmb_StopBits.SelectedIndex = 0;//停止位默认值
            cmb_Parity.SelectedIndex = 0;  //校验位默认值
            //ascii码范围0-127
            //Hex16进制
            //UTF-8UTF-8用1到6个字节编码Unicode字符。用在网页上可以统一页面显示中文简体繁体及其它语言。
            //Unicode码扩展自ASCII字元集。在严格的ASCII中，每个字元用7位元表示，
            //或者电脑上普遍使用的每字元有8位元宽；而Unicode使用全16位元字元集。
            //Unicode能够表示世界上所有的书写语言中可能用於电脑通讯的字元、象形文字和其他符号。
            pic_port.BackgroundImage = Resource._red;   //串口状态指示灯
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(Com_DataReceived);//串口接收数据时间处理
        }
        private void btn_openPort_Click(object sender, EventArgs e)
        {
            if (cmb_port.Items.Count <= 0)
            {
                MessageBox.Show("没有发现串口,请检查线路！");
                return;
            }

            if (serialPort1.IsOpen == false)
            {
                serialPort1.PortName = cmb_port.SelectedItem.ToString();
                serialPort1.BaudRate = Convert.ToInt32(cmb_BaudRate.SelectedItem.ToString());
                serialPort1.DataBits = Convert.ToInt32(cmb_DataBits.SelectedItem.ToString());
                serialPort1.StopBits = (StopBits)Convert.ToInt32(cmb_StopBits.SelectedItem.ToString());
                serialPort1.Parity = (Parity)Convert.ToInt32(cmb_Parity.SelectedIndex.ToString());
                try
                {
                    serialPort1.Open();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
                pic_port.BackgroundImage = Resource._green;
                btn_openPort.Text = "关闭串口";
            }
            else
            {
                try
                {
                    serialPort1.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                pic_port.BackgroundImage = Resource._red;
                btn_openPort.Text = "打开串口";
            }
            cmb_port.Enabled = !serialPort1.IsOpen;
            cmb_BaudRate.Enabled = !serialPort1.IsOpen;
            cmb_Parity.Enabled = !serialPort1.IsOpen;
            cmb_DataBits.Enabled = !serialPort1.IsOpen;
            cmb_StopBits.Enabled = !serialPort1.IsOpen;
        }

        private void Com_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            byte[] ReDatas = new byte[serialPort1.BytesToRead];
            serialPort1.Read(ReDatas, 0, ReDatas.Length);//读取数据
            string a = serialPort1.ReadExisting();
            AddData(ReDatas);//输出数据
        }

        private void AddContent(string content)
        {
            this.BeginInvoke(new MethodInvoker(delegate
            {
                if (txt_receive.Text.Length > 0)
                {
                    txt_receive.AppendText("\r\n");
                }
                txt_receive.AppendText(content);
            }));
        }

        public void AddData(byte[] data)
        {
            AddContent(new ASCIIEncoding().GetString(data));
        }

        public bool SendData(byte[] data)
        {
            if (serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Write(data, 0, data.Length);//发送数据
                    return true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            else
            {
                MessageBox.Show("串口未打开", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            return false;
        }
        private void btn_sendData_Click(object sender, EventArgs e)
        {
            byte[] sendData = null;
            sendData = Encoding.ASCII.GetBytes(txt_send.Text.Trim());
            SendData(sendData);
        }

        private void btn_clearSend_Click(object sender, EventArgs e)
        {
            txt_send.Clear();
        }

        private void btn_clearReceive_Click(object sender, EventArgs e)
        {
            txt_receive.Clear(); 
        }





    }
}
